package com.ccteam.fluidmusic.ui.nowplaying

import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.transition.Slide
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.ccteam.fluidmusic.R
import com.ccteam.fluidmusic.databinding.FragmentNowPlayingBinding
import com.ccteam.fluidmusic.fluidmusic.common.utils.AlbumArtCache
import com.ccteam.fluidmusic.utils.PaletteUtils
import com.ccteam.fluidmusic.utils.TRANSITION_FAST
import com.ccteam.fluidmusic.ui.MainActivityViewModel
import com.google.android.material.color.MaterialColors
import com.google.android.material.tabs.TabLayoutMediator
import com.google.android.material.transition.MaterialContainerTransform
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 *
 * @author Xiaoc
 * @since 2021/1/7
 *
 * 正在播放页面的显示
 */
@AndroidEntryPoint
class NowPlayingFragment : Fragment() {

    private var _binding: FragmentNowPlayingBinding? = null
    private val binding get() = _binding!!

    private val nowPlayingViewModel by viewModels<NowPlayingViewModel>()

    private val mainActivityViewModel by activityViewModels<MainActivityViewModel>()

    @Inject lateinit var albumArtCache: AlbumArtCache

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        returnTransition = Slide().apply {
            duration = TRANSITION_FAST
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentNowPlayingBinding.inflate(layoutInflater,container,false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        val transitionPlaceHolder = requireActivity().findViewById<View>(R.id.transition_placeholder)
        enterTransition = MaterialContainerTransform().apply {
            startView = transitionPlaceHolder
            endView = binding.containerNowPlaying
            duration = 300L
            isElevationShadowEnabled = false
            startContainerColor = MaterialColors.getColor(view,R.attr.colorSurface)
            endContainerColor = MaterialColors.getColor(view,R.attr.colorSurface)
        }

        binding.viewpagerNowPlaying.adapter = NowPlayingPagerAdapter()
        TabLayoutMediator(binding.tabNowPlaying,binding.viewpagerNowPlaying){ tab, position ->
            when(position){
                0 -> tab.text = getString(R.string.now_playing_tab_playlist)
                1 -> tab.text = getString(R.string.now_playing_tab_music)
                2 -> tab.text = getString(R.string.now_playing_tab_lyrics)
            }
        }.attach()
        binding.viewpagerNowPlaying.setCurrentItem(1,false)

        nowPlayingViewModel.enableFluidMode.observe(viewLifecycleOwner, { enableFluidMusic ->
            /**
             * 当处于灵动模式时才去观察对应封面变化，改变背景
             */
            if(enableFluidMusic){
                mainActivityViewModel.mediaAlbumArt.removeObserver(mediaAlbumArtObserver)
                mainActivityViewModel.mediaAlbumArt.observe(viewLifecycleOwner,mediaAlbumArtObserver)
            }
            binding.fluidBackground.isVisible = enableFluidMusic

            /**
             * 如果灵动模式更改，则设置其默认的FluidColor颜色
             * 如果是灵动色彩模式，则为白色，否则为主色调
             */
            val defaultColor = if(enableFluidMusic){
                Pair(requireContext().getColor(R.color.white_alphaf0),requireContext().getColor(R.color.white_alpha2e))
            } else {
                val colorPrimary = MaterialColors.getColor(
                    view,R.attr.colorPrimary)
                Pair(colorPrimary,
                    PaletteUtils.rgb2Argb(colorPrimary))
            }
            nowPlayingViewModel.defaultColor = defaultColor
            nowPlayingViewModel.setDefaultFluidColor(defaultColor)
        })

        nowPlayingViewModel.fluidColor.observe(viewLifecycleOwner, {
            if(it == null){
                return@observe
            }
            if(nowPlayingViewModel.enableFluidMode.value == false){
                updateTabTextColor(it)
            }
        })
    }

    private val mediaAlbumArtObserver = Observer<Pair<Uri?,Uri?>> {
        updateFluidBackground(it)
    }

    private fun updateTabTextColor(arrayPair: Pair<Int,Int>){
        binding.tabNowPlaying.setTabTextColors(arrayPair.second,arrayPair.first)
    }

    private fun updateFluidBackground(albumArtUri: Pair<Uri?, Uri?>){
        val (cacheKeyUri,realParseUri) = albumArtUri

        if(cacheKeyUri != null && realParseUri != null){
            viewLifecycleOwner.lifecycleScope.launch {
                albumArtCache.resolveBitmapByUri(
                    cacheKeyUri,
                    realParseUri,
                    isFull = false,
                    {},{ bitmap ->
                        binding.fluidBackground.updateAlbumArt(bitmap)
                    }
                )
            }
        } else {
            binding.fluidBackground.updateAlbumArt(null)
        }
    }

    inner class NowPlayingPagerAdapter : FragmentStateAdapter(this) {

        override fun getItemCount(): Int = 3

        override fun createFragment(position: Int): Fragment {
            return when (position) {
                0 -> PlaylistPlayerFragment.newInstance()
                1 -> ControlPlayerFragment.newInstance()
                2 -> LyricsPlayerFragment.newInstance()
                else ->
                    throw IllegalArgumentException("错误的布局参数")
            }
        }

    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

}